// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
//@ts-ignore
import getMessage from 'ts-msg-handler'
import { feedApi } from '/api/feed'
import { knowAboutApi } from '/api/knowAbout'
import { userApi } from '/api/user'
import { checkAuth } from '/store/actions'
import { getServer, isLogin } from '/store/mutations'
import { GlobalData } from '/store/state'
import { $event } from '/utils'

Component({
  properties: {
    neeTabPadding: { type: Boolean, value: false },
    canClick: { type: Boolean, value: false },
    list: { type: null, value: [] },
    isHome: { type: Boolean, value: false },
    isDetail: { type: Boolean, value: false },
    hideTopic: { type: Boolean, value: false },
    // 新增动态分类
    category: { type: Number, value: 0 },
    isknowabout: { type: Boolean, value: false },
    detail: { type: Boolean, value: false },
  },
  data: {
    likeLock: false, // 点赞锁
    access: GlobalData.access,
    morelist: [],
    user: {} as DomoUser,
    wendaId: 0,
    feedId: 0,
    index: 0,
    show: false,
    repostable: {} as any,
    recommend: false,
    categories: [] as DomoFeedCategory[],
    chooseCategories: [] as number[],
    /** 如果是已推荐,存一个模板用来对比 */
    tempeletCategories: [] as number[],
    activeFeed: {} as DomoFeed,
    width: 0,
  },
  lifetimes: {
    async attached() {
      $event.on('after:boot', this, () => {
        this.setData({ access: GlobalData.access })
      })
      $event.on('after:onLike', this, (feedId) => {
        const indexList = this.properties.list.map((item: any) => item.id)
        const index = indexList.indexOf(feedId)
        if (index < 0) return
        this.like(index)
      })
      $event.on('after:listcomment', this, (id) => {
        const indexList = this.properties.list.map((item: any) => item.id)
        const index = indexList.indexOf(id)
        if (index < 0) return
        this.comment(index)
      })
      if (isLogin()) {
        const user = wx.getStorageSync(`${getServer()}/logged`).data
        this.setData({ user })
      }
      const categories = await feedApi.categiries()
      wx.getSystemInfo({
        success: (res) => {
          const width = res.screenWidth
          this.setData({ width })
        },
      })
      this.setData({ access: GlobalData.access, categories })
    },
  },
  methods: {
    like(index: number) {
      const list = this.properties.list
      const feed = list[index]
      if (feed.has_liked) {
        this.setData({
          [`list[${index}].has_liked`]: false,
          [`list[${index}].like_count`]: feed.like_count - 1,
        })
      } else {
        this.setData({
          [`list[${index}].has_liked`]: true,
          [`list[${index}].like_count`]: feed.like_count + 1,
        })
      }
    },
    comment(index: number) {
      const list = this.properties.list
      const feed = list[index]
      this.setData({
        [`list[${index}].feed_comment_count`]: feed.feed_comment_count + 1,
      })
    },
    async onLike(event: any) {
      if (this.data.likeLock) return
      await checkAuth()
      const index = +event.currentTarget.dataset.index
      const list = this.properties.list
      const feed = list[index]
      this.data.likeLock = true
      try {
        if (feed.has_liked) {
          this.setData({
            [`list[${index}].has_liked`]: false,
            [`list[${index}].like_count`]: feed.like_count - 1,
          })
          await feedApi.unlikeFeed(feed.id)
        } else {
          this.setData({
            [`list[${index}].has_liked`]: true,
            [`list[${index}].like_count`]: feed.like_count + 1,
          })
          const res = await feedApi.likeFeed(feed.id)
          if (res.amount) {
            $event.emit('showMessage', {
              message: '点赞成功',
              amount: res.amount,
            } as GetRewardMessageReturns)
          }
        }
      } catch (error) {
        wx.showToast({ title: `${getMessage(error.data).getMessage()}`, icon: 'none' })
      }
      this.data.likeLock = false
    },
    onComment(event: any) {
      const data: { feedId: number; index: number } = event.currentTarget.dataset
      $event.emit('showComment', { feedId: +data.feedId, index: data.index })
    },

    // 更多按钮弹出框
    showMore(event: WechatMiniprogram.CustomEvent) {
      const {
        data: { user, chooseCategories, tempeletCategories, list },
      } = this
      const {
        currentTarget: {
          dataset: { feedId, repostable, repostableId: wendaId, index, item },
        },
      } = event

      const abilities: any = GlobalData.userAbilities
      const itemList: any[] = []
      const canDelete =
        (abilities &&
          abilities.some((i: any) => {
            return i.name === '[feed] Delete Feed'
          })) ||
        +item.user_id === +user.id

      if (canDelete) {
        itemList.push('删除')
      } else {
        itemList.push('举报')
      }
      const needAdopt =
        repostable !== '' && repostable.author_id === user.id && !repostable.adoption
      if (needAdopt) {
        itemList.push('采纳')
      }
      const canForbiden =
        abilities &&
        abilities.some((i: any) => {
          return i.name === 'admin:role:show'
        }) &&
        +item.user_id !== +user.id
      if (canForbiden) {
        itemList.push('禁用')
      }
      const canPushRecommend =
        abilities &&
        abilities.some((i: any) => {
          return i.name === '[feed] Push To Category'
        })
      if (canPushRecommend) {
        itemList.push('推荐')
      }
      wx.showActionSheet({
        itemList: itemList,
        success: (res) => {
          switch (itemList[res.tapIndex]) {
            case '举报':
              wx.navigateTo({
                url: `/pages/report/report?type=feed&id=${feedId}`,
              })
              break
            case '采纳':
              this.setData({ wendaId, feedId, index, repostable })
              repostable.offer > 0 ? this.showTost() : this.choose()
              break
            case '禁用':
              wx.showModal({
                title: '提示',
                content: '确定禁用该用户吗?',
                success: (res) => {
                  if (res.confirm) {
                    userApi
                      .deleteUser(item.user_id)
                      .then(() => {
                        wx.showToast({ title: '禁用成功', icon: 'none' })
                      })
                      .catch(() => {
                        wx.showToast({ title: '禁用失败', icon: 'none' })
                      })
                  }
                },
              })
              break
            case '删除':
              wx.showModal({
                title: '提示',
                content: '确定删除该条动态吗?',
                success: (res) => {
                  if (res.confirm) {
                    feedApi
                      .deleteFeed(feedId)
                      .then(() => {
                        wx.showToast({ title: '删除成功', icon: 'none' })
                        // $event.emit('after:changeFeedList', feedId)
                        list.splice(index, 1)
                        this.setData({ list })
                      })
                      .catch(() => {
                        wx.showToast({ title: '删除失败', icon: 'none' })
                      })
                  }
                },
              })
              break
            case '推荐':
              item.categories.length > 0
                ? item.categories.forEach((i: any) => {
                    chooseCategories.push(i.id)
                    tempeletCategories.push(i.id)
                  })
                : ''
              this.setData({
                recommend: true,
                activeFeed: item,
                chooseCategories,
              })
              break
          }
        },
      })
    },
    /** 采纳问题扣费弹窗 */
    showTost() {
      this.setData({ show: true })
    },
    /**关闭弹窗 */
    close() {
      this.setData({ show: false, recommend: false })
    },
    /** 采纳 */
    choose() {
      this.close()
      const {
        data: { wendaId, feedId, index },
      } = this
      knowAboutApi
        .chooseAnswer(wendaId, feedId)
        .then(() => {
          wx.showToast({
            title: '采纳成功',
            icon: 'none',
          })
        })
        .then(() => {
          this.setData({
            [`list[${index}].adoption`]: true,
          })
        })
        .catch(() => {
          wx.showToast({
            title: '采纳失败',
            icon: 'none',
          })
        })
    },
    jumpToDetail(event: WechatMiniprogram.BaseEvent) {
      const {
        currentTarget: {
          dataset: { feedId },
        },
      } = event
      // if (type && type !== 'wendas') return
      wx.navigateTo({ url: `/pages/feed/detail/detail?feedId=${feedId}` })
    },
    toProduct(e: WechatMiniprogram.BaseEvent) {
      if (!this.properties.canClick) return
      const {
        currentTarget: {
          dataset: { item },
        },
      } = e
      wx.navigateTo({
        url:
          item.repostable_type === 'knowledge'
            ? `/index/knowledge/detail/detail?id=${item.repostable.id}`
            : item.repostable_type === 'infos'
            ? `/index/information/detail/detail?id=${item.repostable.id}`
            : item.repostable_type === 'events'
            ? `/pages/activity/detail/detail?id=${item.repostable.id}`
            : `/mall/detail/detail?commodityId=${item.repostable.id}`,
      })
    },
    async viewVideo(e: WechatMiniprogram.CustomEvent) {
      await checkAuth()
      const data = e.currentTarget.dataset
      if (GlobalData.access.video) {
        wx.navigateTo({
          url: `/pages/feed/video/video?feedId=${data.feedId}`,
        })
      } else {
        const feed = this.data.list.find((item: any) => item.id === data.feedId)!
        wx.previewImage({
          current: feed.video!.cover.url,
          urls: [feed.video!.cover.url],
        })
      }
    },
    todetail(e: WechatMiniprogram.BaseEvent) {
      if (!this.properties.canClick) return
      const {
        currentTarget: {
          dataset: { id, index },
        },
      } = e
      wx.navigateTo({
        url:
          +index === 0
            ? `/index/knowAboutDetail/knowAboutDetail?id=${id}`
            : `/pages/theme/detail/detail?id=${id}`,
      })
    },
    /** 选择分类 */
    chooseCategories(e: WechatMiniprogram.CustomEvent) {
      const {
        currentTarget: {
          dataset: { index },
        },
      } = e
      const {
        data: { chooseCategories },
      } = this
      if (chooseCategories.indexOf(index) == -1) {
        chooseCategories.push(index)
      } else {
        chooseCategories.splice(chooseCategories.indexOf(index), 1)
      }
      this.setData({
        chooseCategories,
      })
    },
    /** 确认推荐 */
    async recommend() {
      const {
        data: { chooseCategories, activeFeed, tempeletCategories },
      } = this
      /** 如果没有改变 */
      if (
        activeFeed.categories.length > 0 &&
        chooseCategories.sort().toString() == tempeletCategories.sort().toString()
      ) {
        return
      }
      wx.showLoading({
        title: '设置中',
      })
      if (activeFeed.categories.length > 0) {
        const add = [] as number[]
        const minus = [] as number[]
        chooseCategories.forEach((i: number) => {
          if (tempeletCategories.indexOf(i) === -1) {
            add.push(i)
          }
        })
        tempeletCategories.forEach((i: number) => {
          if (chooseCategories.indexOf(i) === -1) {
            minus.push(i)
          }
        })
        /** 如果只有减少 */
        if (minus.length > 0 && add.length === 0) {
          await minus.forEach(async (i: number) => {
            feedApi.popToCategory(activeFeed.id, i)
          })
          $event.emit('delete:category', { feedId: activeFeed.id, categoryIds: minus })
          wx.hideLoading()
          await wx.showToast({
            title: '设置完成',
            icon: 'none',
          })
          this.close()
          $event.emit('after:changeFeedList')
          return
        } else if (minus.length > 0 && add.length > 0) {
          /** 增减都有 */
          await minus.forEach(async (i: number) => {
            feedApi.popToCategory(activeFeed.id, i)
          })
          $event.emit('delete:category', { feedId: activeFeed.id, categoryIds: minus })
        }
        this.addCategories(activeFeed, add)
      } else {
        this.addCategories(activeFeed, chooseCategories)
      }
    },
    /** 添加推荐 */
    addCategories(feed: DomoFeed, arr: number[]) {
      feedApi
        .pushToCategory(feed.id, arr)
        .then(() => {
          wx.hideLoading()
          wx.showToast({
            title: '设置成功',
          })
          $event.emit('after:changeFeedList')
          this.close()
        })
        .catch(() => {
          wx.showToast({
            title: '设置失败',
            icon: 'none',
          })
          this.close()
        })
    },
  },
})
